//
//  PaperItemCellTableView.m
//  DoingPaper
//
//  Created by zhuxuhong on 16/7/25.
//  Copyright © 2016年 zhuxuhong. All rights reserved.
//

#import "PaperItemCellTableView.h"
#import "PaperQuestionWebCell.h"
#import "PaperInputSelectionCell.h"
#import "PaperQuestionOption.h"
#import "PaperOptionWebCell.h"
#import "PaperDataManager.h"
#import "PaperQuestionAnalysisFooter.h"

@interface PaperItemCellTableView() <UITableViewDelegate,
UITableViewDataSource,
QuestionWebCellDelegate,
OptionWebCellDelegate,
PaperQuestionAnalysisFooterDelegate>
@property(nonatomic,copy)NSString *paperId;
@end

@implementation PaperItemCellTableView
{
    NSIndexPath *lastSelectedCellIndexPath;
    NSString *baseUrl;
    PaperQuestionAnalysisFooter *analysisFooter;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame style:UITableViewStyleGrouped];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self registerClass:[PaperQuestionWebCell class] forCellReuseIdentifier:@"PaperQuestionWebCell"];
        [self registerClass:[PaperInputSelectionCell class] forCellReuseIdentifier:@"PaperInputSelectionCell"];
        [self registerClass:[PaperOptionWebCell class] forCellReuseIdentifier:@"PaperOptionWebCell"];
        
        self.delegate = self;
        self.dataSource = self;
    }
    return self;
}

-(void)endEditing{
    self.editing = false;
}

-(void)setQuestion:(PaperQuestion *)question{
    _question = question;
    baseUrl = [[PaperDataManager sharedManager] paperImagesPathWithId: _question.paperId];

    CGFloat bottomInset = 54;
    self.contentInset = UIEdgeInsetsMake(-34, 0, bottomInset, 0);
    
    [self reloadData];
}

// 对外方法，查看答案
-(void)setIsScanningAnswer:(BOOL)isScanningAnswer{
    _isScanningAnswer = isScanningAnswer;
    
    [self reloadData];
}


#pragma mark UITableView

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 44;
    if (indexPath.row == 0) { //题目webcell
        return (_question.image) ? _question.image.size.height : height;
    }
    if (_question.options.count > 0) { // 选择题
        PaperQuestionOption *op = _question.options[indexPath.row - 1];
        return (op.image) ? op.image.size.height : height;
    }
    return 200; // 非选择题选项
}

-(NSInteger)numberOfSections{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count = _question.options.count;
    if (count > 0) {
        return count + 1;
    }
    return 2; //1 + 1非选择题
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (_question.submited) { // 交卷
        CGFloat h = _question.analysisFooterHeight;
        return h == 0 ? 100 : h;
    }
    return 0; // 预览
}

// footer view
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (_question.submited && _isScanningAnswer) {
        if (!analysisFooter) {
            analysisFooter = [[PaperQuestionAnalysisFooter alloc] initWithDelegate:self];
            [analysisFooter loadContentWithQuestion:_question baseUrl:baseUrl];
        }
        return analysisFooter;
    }
    return nil;
}

-(void)paperMarkScoreFooterDidScore:(float)score selectedBtnIndex:(NSInteger)index{
    NSLog(@"score: %f, index: %ld",score, index);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.allowsSelection = !_question.submited; //已提交卷
    
    if (indexPath.row == 0) {
        return [self headerCellOfTableView:tableView atIndexPath:indexPath];
    }
    
    // 输入题
    if (_question.options.count == 0) {
        return [self inputCellOfTableView:tableView atIndexPath:indexPath];
    }
    
    // 单选题
    if ([_question.qtype isEqualToString:@"1"]) {
        return [self optionCellOfTableView:tableView atIndexPath:indexPath isSingleOption:true];
    }
    
    // 多选题
    if ([_question.qtype isEqualToString:@"2"]) {
        return [self optionCellOfTableView:tableView atIndexPath:indexPath isSingleOption:false];
    }
    
    return nil;
}

#pragma mark - cell

// 题目
-(UITableViewCell*)headerCellOfTableView: (UITableView*)tableView
                             atIndexPath: (NSIndexPath *)indexPath{
    PaperQuestionWebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PaperQuestionWebCell" forIndexPath:indexPath];
    if (!_question.image) {
        [cell loadWebQuestionWithBaseUrl:baseUrl question:_question delegate:self];
    }
    else{
        [cell setQuestionImage: _question.image];
    }
    return cell;
}

// 输入题
-(UITableViewCell*)inputCellOfTableView: (UITableView*)tableView
                            atIndexPath: (NSIndexPath *)indexPath{
    PaperInputSelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PaperInputSelectionCell" forIndexPath:indexPath];
    cell.question = _question;
    return cell;
}

// 单选/多选题
-(UITableViewCell*)optionCellOfTableView: (UITableView*)tableView
                           atIndexPath: (NSIndexPath *)indexPath
                        isSingleOption: (BOOL)single{
    PaperOptionWebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PaperOptionWebCell" forIndexPath:indexPath];
    PaperQuestionOption *op = _question.options[indexPath.row-1]; // 记得-1
    if (!op.image) {
        [cell loadWebOptionContentWithBaseUrl:baseUrl option:op isSingle:single delegate:self];
    }
    else{
        [cell setOptionImage: op.image];
        cell.choosed = false;
    }
    
    // 设置选中项
    for (NSNumber *op in _question.userOptions) {
        cell.choosed = [op integerValue] == indexPath.row-1 ? true : false;
    }
    return cell;
}


#pragma mark - 选中逻辑
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return;
    }
    if ([_question.qtype isEqualToString:@"1"]) {
        [self singleCellOfTableView:tableView didSelectAtIndexPath:indexPath];
    }
    else if ([_question.qtype isEqualToString:@"2"]) {
        [self multiCellOfTableView:tableView didSelectAtIndexPath:indexPath];
    }
}

// 单选题选中一个
-(void)singleCellOfTableView: (UITableView*)tableView
        didSelectAtIndexPath:(NSIndexPath *)indexPath{
    if (lastSelectedCellIndexPath) {
        PaperOptionWebCell *lastCell = [tableView cellForRowAtIndexPath:lastSelectedCellIndexPath];
        lastCell.choosed = false;
    }
    // 选中项
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    PaperOptionWebCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.choosed = true;
    lastSelectedCellIndexPath = indexPath;
    
    [_question.userOptions removeAllObjects];
    [_question.userOptions addObject:@(lastSelectedCellIndexPath.row-1)];
    
    NSLog(@"userOptions: %@",_question.userOptions);

    // 下一页
    [[NSNotificationCenter defaultCenter]postNotificationName:@"DidSelectOptionNoti" object:nil];
}

// 多选题
-(void)multiCellOfTableView: (UITableView*)tableView
        didSelectAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    PaperOptionWebCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.choosed = !cell.choosed;
    cell.choosed ? [_question.userOptions addObject:@(indexPath.row-1)] : [_question.userOptions removeObject:@(indexPath.row-1)];
    NSLog(@"userOptions: %@",_question.userOptions);
}

-(void)questionWebCellContentDidLoadWithQuestion:(PaperQuestion *)question{
//    NSLog(@"question web cell did load: %lf",question.image.size.height);
    [self reloadData];
}

-(void)optionWebCellContentDidLoadWithOption:(PaperQuestionOption *)option{
//    NSLog(@"option web cell did load: %lf",option.image.size.height);
    [self reloadData];
}

-(void)analysisFooter:(PaperQuestionAnalysisFooter *)footer didLoadWithQuestion:(PaperQuestion *)question{
//    NSLog(@"analysisFooter did load: %lf",question.analysisFooterHeight);
    [self reloadData];
}

@end
